import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Radio, Message } from '@teamix/ui';
import exceed from 'utils/apimap';
import intl from '../../locale';

const { pathResource } = window.FORCE;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 4,
  },

  wrapperCol: {
    span: 20,
  },
};

const radioList = [
  {
    value: 'NO_NEED_TO',
    label: intl.get({
      id: 'code-assets.components.ignoreIssueModal.NoProcessingRequired',
      defaultMessage: '无需处理',
    }),
  },

  {
    value: 'FALSE_POSITIVE',
    label: intl.get({
      id: 'code-assets.components.ignoreIssueModal.FalsePositives',
      defaultMessage: '误报',
    }),
  },

  {
    value: 'REPEAT',
    label: intl.get({
      id: 'code-assets.components.ignoreIssueModal.Repeat',
      defaultMessage: '重复',
    }),
  },

  {
    value: 'OTHERS',
    label: intl.get({
      id: 'code-assets.components.ignoreIssueModal.Other',
      defaultMessage: '其他',
    }),
  },
];

export default class TagModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    onCancel: PropTypes.func,
    onClose: PropTypes.func,
    formSubmit: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      isModalOpen: props.isModalOpen || false,
      submitting: false,
    };
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    const { onClose } = this.props;
    this.setState({
      isModalOpen: false,
    });

    onClose && onClose();
  };

  onHandleSubmit = () => {
    const { issue } = this.props;
    if (this.state.submitting) return;
    const formData = this.field.getValues();
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        this.ignoreIsssue({
          detail: issue,
          reason: formData.reason,
          notes: formData.notes || '',
        });
      } else {
        this.setState({ submitting: false });
      }
    });
  };

  messageValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (value.length > 1000) {
      callback(
        intl.get({
          id: 'code-assets.components.ignoreIssueModal.TheDescriptionCannotExceedCharacters',
          defaultMessage: '描述长度不能超过1000',
        }),
      );
    } else {
      callback();
    }
  };

  // 创建CR
  ignoreIsssue(formData) {
    const { onSuccess } = this.props;
    exceed
      .fetch({
        api: 'project.build.issue.ignore',
        params: { projectId: pathResource.id },
        data: formData,
      })
      .then((result) => {
        Message.success({
          title: intl.get({
            id: 'code-assets.components.ignoreIssueModal.ProblemIgnored',
            defaultMessage: '问题忽略成功',
          }),
        });

        onSuccess &&
          onSuccess({
            ...formData.detail,
            status: result.status,
          });

        this.onClose();
        this.setState({ submitting: false });
      })
      .fail(() => {
        this.setState({ submitting: false });
      });
  }

  render() {
    const { field } = this;
    const { init } = this.field;

    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            visible
            onClose={this.onClose}
            onCancel={this.onClose}
            okProps={{
              loading: this.state.submitting,
            }}
            onOk={this.onHandleSubmit}
            title={intl.get({
              id: 'code-assets.components.ignoreIssueModal.Ignore',
              defaultMessage: '忽略问题',
            })}
            style={{
              width: '500px',
            }}
          >
            <Form labelAlign="top" field={field}>
              <div>
                <Message
                  title={intl.get({
                    id: 'code-assets.components.ignoreIssueModal.IfThisIssueIsIgnored',
                    defaultMessage: '忽略后当前分支不再报出该问题，其他分支不受影响',
                  })}
                  type="notice"
                />
              </div>
              <FormItem
                label={intl.get({
                  id: 'code-assets.components.ignoreIssueModal.IgnoreReason',
                  defaultMessage: '忽略原因',
                })}
                required
                {...formItemLayout}
              >
                <Radio.Group
                  dataSource={radioList}
                  {...init('reason', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.components.ignoreIssueModal.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                    ],
                  })}
                />
              </FormItem>
              {this.field.getValue('reason') === 'OTHERS' && (
                <FormItem label="" {...formItemLayout}>
                  <Input.TextArea
                    {...init('notes', {
                      rules: [{ validator: this.messageValidator }],
                    })}
                    placeholder={intl.get({
                      id: 'code-assets.components.ignoreIssueModal.PleaseDescriptionIgnoreReason',
                      defaultMessage: '请说明忽略原因',
                    })}
                  />
                </FormItem>
              )}
            </Form>
          </Dialog>
        ) : null}
        {this.props.trigger && React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
